package com.seamtop.cuber.web.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seamtop.cuber.common.base.DataObject;
import com.seamtop.cuber.common.entriy.*;
import com.seamtop.cuber.common.metadata.TableMetaData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zongjunfeng on 2015/9/1.
 */
public class SearchParamsUtil {

    private static final Logger LOG = LoggerFactory.getLogger(SearchParamsUtil.class);

    public static String combSearchParams(ESSearchBean esSearchBean){
        List<String> periodList = esSearchBean.getPeriodList();
        HashMap<String,String> filterMap = esSearchBean.getFilterMap();
        HashMap<String,List<String>> shouldMap = new HashMap<String, List<String>>();
        shouldMap.put("period",periodList);
        if(esSearchBean.getReducerId() != null){
            filterMap.put("reducer",esSearchBean.getReducerId());
        }else if(esSearchBean.getCounterId() != null){
            filterMap.put("counter",esSearchBean.getCounterId());
        }
        return combSearchParams(shouldMap,filterMap);
    }

    public static String combSearchParams(HashMap<String,List<String>> esShouldParamsMap,HashMap<String,String> esMustParamsMap){
        JSONObject qo = new JSONObject();
        JSONArray mfo = new JSONArray();
        if(esMustParamsMap != null && esMustParamsMap.size()>0){
            for(String s:esMustParamsMap.keySet()){
                SearchBean searchBean = new SearchBean();
                searchBean.setDefault_field(s);
                searchBean.setQuery("\"" + esMustParamsMap.get(s) + "\"");
                JSONObject tfo = new JSONObject();
                tfo.put("query_string",searchBean);
                mfo.add(tfo);
            }
        }

        JSONArray sfo = new JSONArray();
        if(esShouldParamsMap != null && esShouldParamsMap.size()>0){
            for(String s:esShouldParamsMap.keySet()){
                List<String> olist = esShouldParamsMap.get(s);
                String v = "";
                for(int i=0;i<olist.size();i++){
                    v += "\"" + olist.get(i) +  "\"";
                    v += " ";
                }
                SearchBean searchBean = new SearchBean();
                searchBean.setDefault_field(s);
                searchBean.setQuery(v);
                JSONObject tfo = new JSONObject();
                tfo.put("query_string",searchBean);
                sfo.add(tfo);
            }
        }


        JSONObject p = new JSONObject();
        p.put("must",mfo);
        p.put("should",sfo);
        JSONObject bfo = new JSONObject();
        bfo.put("bool",p);
        qo.put("query", bfo);

        //ƴ������ʽ
        JSONObject sortObj = new JSONObject();
        sortObj.put("order", "asc");
        JSONObject psoftObj = new JSONObject();
        psoftObj.put("period",sortObj);
        qo.put("sort",psoftObj);
        System.out.println(qo.toJSONString());
        return qo.toJSONString();
    }


    public static ESResult parseCounterSEResult(String result) throws Exception{
        LOG.info("ES result:" + result);
        ESResult esResult = null;
        JSONObject seJson = JSONObject.parseObject(result);
        if(seJson != null){
            JSONObject hitsObj = seJson.getJSONObject("hits");
            JSONArray hitsArray = hitsObj.getJSONArray("hits");
            esResult = new ESResult();
            List<ESResultItem> esResultItemList = new ArrayList<ESResultItem>();
            for(int i=0;i<hitsArray.size();i++){
                ESResultItem esResultItem = new ESResultItem();
                HashMap<String,String> propertiesMap = new HashMap<String, String>();
                esResultItem.setPropertiesMap(propertiesMap);
                JSONObject resHits = hitsArray.getJSONObject(i);
                JSONObject sourceObj = resHits.getJSONObject("_source");
                String id = resHits.getString("_id");
                String [] idArray = id.split("\\|");
                String counterId = idArray[0].split("_")[0];
                String period = idArray[0].split("_")[1];
                esResultItem.setPeriod(period);
                esResultItem.setId(id);
                esResultItem.setDataFact(counterId);
                for(String s:sourceObj.keySet()){
                    if("counter".equals(s)){

                    }else if("period".equals(s)){

                    }else if("value".equals(s)){
                        esResultItem.setValue(sourceObj.getString("value"));
                    }else{
                        String v = sourceObj.getString(s);
                        v = URLDecoder.decode(v,"UTF-8");
                        propertiesMap.put(s,v);
                    }
                }
                esResultItemList.add(esResultItem);
            }
            esResult.setItemList(esResultItemList);
            int total = Integer.parseInt(hitsObj.getString("total"));
            esResult.setTotal(total);
        }
        return esResult;
    }


    public static ESResult parseSEResult(String result) throws Exception{
        LOG.info("ES result:" + result);
        ESResult esResult = null;
        JSONObject seJson = JSONObject.parseObject(result);
        if(seJson != null){
            JSONObject hitsObj = seJson.getJSONObject("hits");
            JSONArray hitsArray = hitsObj.getJSONArray("hits");
            esResult = new ESResult();
            List<ESResultItem> esResultItemList = new ArrayList<ESResultItem>();
            for(int i=0;i<hitsArray.size();i++){
                ESResultItem esResultItem = new ESResultItem();
                HashMap<String,String> propertiesMap = new HashMap<String, String>();
                esResultItem.setPropertiesMap(propertiesMap);
                JSONObject resHits = hitsArray.getJSONObject(i);
                JSONObject sourceObj = resHits.getJSONObject("_source");
                String id = resHits.getString("_id");
                String [] idArray = id.split("\\|");
                String reducerId = idArray[0].split("_")[0];
                String period = idArray[0].split("_")[1];
                esResultItem.setId(id);
                String reducerSet = resHits.getString("_type");
                esResultItem.setPeriod(period);
                esResultItem.setReducerSet(reducerSet);
                esResultItem.setReducer(reducerId);
                for(String s:sourceObj.keySet()){
                    if("reducer".equals(s)){

                    }else if("period".equals(s)){

                    }else if("value".equals(s)){
                        esResultItem.setValue(sourceObj.getString("value"));
                    }else{
                        String v = sourceObj.getString(s);
                        v = URLDecoder.decode(v,"UTF-8");
                        propertiesMap.put(s,v);
                    }
                }
                esResultItemList.add(esResultItem);
            }
            esResult.setItemList(esResultItemList);
            int total = Integer.parseInt(hitsObj.getString("total"));
            esResult.setTotal(total);
        }
        return esResult;
    }

}
